#include <func.h>
#include <sys/sendfile.h>

#define MAX_BUFFER_SIZE 1024   // 缓冲区大小
#define SERVER_PORT 8080       // 服务器端口号
#define BIG_FILE 1048576       // 大文件的阈值

typedef struct train_s {
    int length;
    char data[1024];
}train_t;

// 函数定义：将本地文件上传至服务器端
int uploadFileToServer(int netfd, char* filename, char* path) {
    int fd;
    struct stat statbuf;
    off_t filesize;
    ssize_t bytesSent;
    train_t train;

    // 打开本地文件
    fd = open(path, O_RDONLY);
    if (fd < 0) {
        perror("Error opening local file");
        return -1;
    }

    // 获取本地文件状态信息
    if (fstat(fd, &statbuf) < 0) {
        perror("Error getting file status");
        close(fd);
        return -1;
    }

    // 发送文件名到服务器
    train.length = strlen(filename);
    memcpy(train.data, filename, train.length);
    send(netfd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);

    // 发送文件大小到服务器
    filesize = statbuf.st_size;
    train.length = sizeof(filesize);
    memcpy(train.data, &filesize, train.length);
    send(netfd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);

    // 发送文件内容到服务器
    if (filesize >= BIG_FILE) {
        while ((bytesSent = sendfile(netfd, fd, NULL, filesize)) > 0) {
            filesize -= bytesSent;
        }
    }
    else {
        while ((bytesSent = read(fd, train.data, sizeof(train.data))) > 0) {
            train.length = bytesSent;
            send(netfd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);
        }
    }

    // 关闭本地文件
    close(fd);

    // 发送一个长度为 0 的数据包表示文件传输完成
    train.length = 0;
    send(netfd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);

    return 0;
}
